package com.wordlearning.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wordlearning.app.entity.StudyPlan;
import com.wordlearning.app.entity.WordSet;
import com.wordlearning.app.repository.StudyPlanRepository;
import com.wordlearning.app.repository.WordSetRepository;
import com.wordlearning.app.service.StudyPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class StudyPlanServiceImpl implements StudyPlanService {

    private final StudyPlanRepository studyPlanRepository;
    private final WordSetRepository wordSetRepository;

    @Autowired
    public StudyPlanServiceImpl(StudyPlanRepository studyPlanRepository, WordSetRepository wordSetRepository) {
        this.studyPlanRepository = studyPlanRepository;
        this.wordSetRepository = wordSetRepository;
    }

    @Override
    @Transactional
    public StudyPlan createStudyPlan(StudyPlan studyPlan) {
        // 检查wordSetId是否存在
        if (studyPlan.getWordSetId() != null) {
            wordSetRepository.selectById(studyPlan.getWordSetId())
                    .orElseThrow(() -> new IllegalArgumentException("Word set not found with id: " + studyPlan.getWordSetId()));
        }
        
        if (studyPlan.getStartDate() == null) {
            studyPlan.setStartDate(LocalDate.now());
        }
        
        studyPlanRepository.insert(studyPlan);
        return studyPlan;
    }

    @Override
    public List<StudyPlan> getAllStudyPlans() {
        return studyPlanRepository.selectList(null);
    }

    @Override
    public List<StudyPlan> getStudyPlansByUserId(Long userId) {
        return studyPlanRepository.findByUserId(userId);
    }

    @Override
    public List<StudyPlan> getActiveStudyPlansByUserId(Long userId) {
        return studyPlanRepository.findByUserIdAndStatus(userId, "ACTIVE");
    }

    @Override
    public Optional<StudyPlan> getStudyPlanById(Long id) {
        return studyPlanRepository.selectById(id);
    }

    @Override
    @Transactional
    public StudyPlan updateStudyPlan(Long id, StudyPlan studyPlan) {
        StudyPlan existingStudyPlan = studyPlanRepository.selectById(id)
                .orElseThrow(() -> new IllegalArgumentException("Study plan not found with id: " + id));

        // 检查wordSetId是否存在并更新
        if (studyPlan.getWordSetId() != null) {
            WordSet wordSet = wordSetRepository.selectById(studyPlan.getWordSetId())
                    .orElseThrow(() -> new IllegalArgumentException("Word set not found with id: " + studyPlan.getWordSetId()));
            existingStudyPlan.setWordSetId(studyPlan.getWordSetId());
        }

        existingStudyPlan.setName(studyPlan.getName());
        existingStudyPlan.setDailyTarget(studyPlan.getDailyTarget());
        existingStudyPlan.setStartDate(studyPlan.getStartDate());
        existingStudyPlan.setEndDate(studyPlan.getEndDate());
        existingStudyPlan.setCompletedCount(studyPlan.getCompletedCount());
        existingStudyPlan.setStatus(studyPlan.getStatus());

        studyPlanRepository.updateById(existingStudyPlan);
        return existingStudyPlan;
    }

    @Override
    @Transactional
    public void deleteStudyPlan(Long id) {
        if (studyPlanRepository.selectById(id) == null) {
            throw new IllegalArgumentException("Study plan not found with id: " + id);
        }
        studyPlanRepository.deleteById(id);
    }

    @Override
    @Transactional
    public StudyPlan completeDailyTask(Long studyPlanId, Integer completedCount) {
        StudyPlan studyPlan = studyPlanRepository.selectById(studyPlanId)
                .orElseThrow(() -> new IllegalArgumentException("Study plan not found with id: " + studyPlanId));
        

        if (studyPlan.getStatus().equals("COMPLETED")) {
            throw new IllegalArgumentException("Study plan is already completed");
        }

        studyPlan.setCompletedCount(studyPlan.getCompletedCount() + completedCount);
        
        // 检查是否完成整个计划
        if (studyPlan.getWordSetId() != null) {
            Optional<WordSet> wordSetOptional = wordSetRepository.selectById(studyPlan.getWordSetId());
            if (wordSetOptional.isPresent() && wordSetOptional.get().getWords() != null && 
                studyPlan.getCompletedCount() >= wordSetOptional.get().getWords().size()) {
                studyPlan.setStatus("COMPLETED");
                studyPlan.setEndDate(LocalDate.now());
            }
        }

        studyPlanRepository.updateById(studyPlan);
        return studyPlan;
    }

    @Override
    @Transactional
    public StudyPlan changeStatus(Long studyPlanId, String status) {
        StudyPlan studyPlan = studyPlanRepository.selectById(studyPlanId)
                .orElseThrow(() -> new IllegalArgumentException("Study plan not found with id: " + studyPlanId));

        studyPlan.setStatus(status);
        if (status.equals("COMPLETED") && studyPlan.getEndDate() == null) {
            studyPlan.setEndDate(LocalDate.now());
        }

        studyPlanRepository.updateById(studyPlan);
        return studyPlan;
    }
}